In Python, a set is an unordered collection of unique, immutable objects. Sets are mutable, meaning you can add and remove items, but the items themselves must be immutable (like numbers, strings, or tuples).
Sets can be created using curly braces {} or the set() constructor:
{} creates an empty dictionary, not an empty set. Use set() for empty sets.
| Operation | Syntax | Description | Example |
|---|---|---|---|
| Union | | or union() |
Elements in either set | A | B |
| Intersection | & or intersection() |
Elements in both sets | A & B |
| Difference | - or difference() |
Elements in A but not B | A - B |
| Symmetric Difference | ^ or symmetric_difference() |
Elements in either set but not both | A ^ B |
| Method | Description | Example |
|---|---|---|
add(element) |
Adds an element to the set | s.add(5) |
remove(element) |
Removes an element (raises error if not found) | s.remove(5) |
discard(element) |
Removes element (no error if not found) | s.discard(5) |
pop() |
Removes and returns arbitrary element | s.pop() |
clear() |
Removes all elements | s.clear() |
update(iterable) |
Adds multiple elements | s.update([1,2,3]) |
Frozen sets are immutable versions of sets. Once created, they cannot be modified.